package com.my.mail2.service.impl.other;

import com.alibaba.fastjson.JSON;
import com.my.mail2.service.impl.AbstractEmailService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.simplejavamail.api.email.Email;
import org.simplejavamail.api.email.EmailPopulatingBuilder;
import org.simplejavamail.api.mailer.AsyncResponse;
import org.simplejavamail.api.mailer.Mailer;
import org.simplejavamail.email.EmailBuilder;
import org.simplejavamail.mailer.MailerBuilder;
import org.springframework.stereotype.Service;

/**
 * 抽象Umail邮箱基础服务
 */
@Data
@Slf4j
@Service
public class AbstractUmailService extends AbstractEmailService {

    private String host;

    private Integer port;

    private String password;

    private String fromName;

    private String fromAddress;

    private Mailer mailer;

    private Mailer getUmailClient() {
        if (mailer == null) {
            synchronized (AbstractUmailService.class) {
                if (mailer == null) {
                    this.mailer = MailerBuilder
                            .withSMTPServer(host, port, fromAddress, password)
                            .withSessionTimeout(10 * 1000)
                            .clearEmailAddressCriteria() // turns off email validation
                            .withDebugLogging(false)
                            .buildMailer();
                }
            }
        }
        return mailer;
    }

    @Override
    public boolean sendEmail(String toAddress, String subject, String htmlBody, String textBody) {
        EmailPopulatingBuilder builder = EmailBuilder.startingBlank().
                from(fromName, fromAddress).
                to(toAddress, toAddress).
                withSubject(subject);
        // 设置邮件内容
        builder.withHTMLText(htmlBody);
        builder.withPlainText(textBody);
        Email email = builder.buildEmail();
        AsyncResponse response = this.getUmailClient().sendMail(email, true);
        if (response != null) {
            response.onException(e -> {
                log.error("umail 发送邮件异常：{}, {}", e.getCause(), email);
                // 错误重试
                mailer.sendMail(email);
            });
        }
        log.info("umail 发送邮件结果：{}", JSON.toJSON(response));
        return true;
    }
}
